#include "mystdio.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>

static MyFile *BuyFile(int fd,int flag)
{
  MyFile *f = (MyFile*)malloc(sizeof(MyFile));
  if(f ==NULL)
  {
    return NULL;
  }
  f->bufferlen=0;
  f->fileno=fd;
  f->flag=flag;
  f->flush_method=LINE_FLUSH;
  memset(f->outbuffer,0,sizeof(f->outbuffer));//结构体初始化

  return f;
}
MyFile *MyFopen(const char * path,const char *mode)
{
   int fd = -1;
   int flag = 0;
   if(strcmp(mode,'w') == 0)
   {
      flag = O_CREAT | O_WRONLY | O_TRUNC;//打开模式
      fd = open(path,flag,0666);
   }
   else if(strcmp(mode,'a') == 0)
   {
      flag = O_CREAT | O_WRONLY | O_APPEND;
      fd = open(path,flag,0666);
   }
   else if(strcmp(mode,'r') == 0)
   {
      flag = O_RDWR;
      fd =open(path,flag);
   }
   else 
   {
         //TODO
   }
   if(fd < 0)
   {
     return NULL;
   }

   return BuyFile();//该函数为打开文件，当打开文件的路径，模式，权限确定后，为文件创建struct_file，buy为结构体进行了初始化
   
}

void Myclose(MyFile *)
{

}

int MyFwrite(MyFile * flie,void *str,int len)
{
  //写入是拷贝
   memcpy(file->outbuffer+file->bufferlen,str,len);
   file->bufferlen+=len;
  //.尝试判断是否满足刷新条件
  if((file->flush_method&LINE_FLUSH)&& file->outbuffer[file->bufferlen-1]= '\n')
  {
    MyFFlush(file);
  }
   return 0;
}

void MyFFlush(MyFile *file)
{
  int n=write(file->fileno,file->outbuffer,file->bufferlen);
  (void)n;
  file->bufferlen=0;
}
